<template>
  <div class="container login">
    <img src="../../../static/imgs/logo.svg" alt="" class="login-logo">
    <form class="form-container">
      <input type="number" class="form-control" v-model="username" placeholder="请输入手机号" />
      <input type="password" class="form-control" v-model="password" placeholder="请输入密码" />
    </form>
    <button @click="goInLogin" type="primary" class="but-login">登录</button>
  </div>
</template>

<script>
import API from '@/utils/api'

export default {
  data () {
    return {
      username: '',
      password: '',
      motto: 'Hello World',
      userInfo: {}
    }
  },
  methods: {
    goToShopList () {
      wx.navigateTo({
        url: '../shopList/main?username=' + this.username
      })
    },
    goInLogin () {
      let that = this
      let data = {
        username: this.username,
        password: this.password
      }
      wx.showLoading({
        title: '登录中'
      })
      wx.request({
        url: API.USRE.LOGIN,
        method: 'POST',
        data,
        header: {
          'content-type': 'application/json' // 默认值
        },
        success (res) {
          if (res.data.code === 0) {
            let user = res.data.data
            user.username = that.username
            wx.setStorage({
              key: 'user',
              data: JSON.stringify(user)
            })
            wx.setStorage({
              key: 'username',
              data: JSON.stringify(data)
            })
            wx.setStorageSync('SESSID', res.header['Set-Cookie'])
            that.goToShopList()
          } else {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 2000
            })
          }
          wx.hideLoading()
        }
      })
    },
    getUserInfo () {
      // 调用登录接口
      try {
        const value = wx.getStorageSync('username')
        if (value) {
          let data = JSON.parse(value)
          this.username = data.username
          this.password = data.password
        }
      } catch (e) {
        this.username = ''
        this.password = ''
      }
    }
  },
  created () {
    // 调用应用实例的方法获取全局数据
    this.getUserInfo()
  }
}
</script>

<style scoped>
  .login {
    justify-content: center
  }
  .login-logo {
    width: 150rpx;
    height: 150rpx;
    margin-bottom: 100rpx;
  }
 .form-container {
   width: 90%;
 }
 .form-container input {
   border: 1px solid #666;
   margin-bottom: 20rpx;
   border-radius: 5px;
   padding: 10rpx;
   font-size: 32rpx;
 }
 .but-login {
   width: 90%;
 }
</style>
